package com.gopay.bis.service.bank.impl.ebank;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.ebank.BocB2bManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BocConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.boc.ebank.BocB2bMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * @BocB2bBankServiceImpl.java
 * @author wanggang
 * @2013-11-4 下午2:19:15 www.gopay.com.cn Inc.All rights reserved.
 */
public class BocB2bBankServiceImpl implements BankInteractRemoteService {

	@Resource(name = "bocB2bManager")
	private BocB2bManager bocB2bManager;
	

	/**
	 * 中行支付类请求
	 * 
	 * @param BaseMessage
	 * @return Result
	 */
	@Override
	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		try {
			BocB2bMessage messageB2B = new BocB2bMessage();
			BeanUtils.copyProperties(base, messageB2B);
			messageB2B = (BocB2bMessage) bocB2bManager.sign(messageB2B);
			base.setBankOrderId(base.getOrderId());
			result.setDefaultModel(messageB2B);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6028);
		}
		return result;
	}

	@Override
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		try {
			BocB2bMessage messageB2B = new BocB2bMessage();
			BeanUtils.copyProperties(base, messageB2B);
			boolean flag = (Boolean) bocB2bManager.verify(messageB2B);
			result.setDefaultModel(flag);
			result.setSuccess(true);

			Map<String, String> param = new HashMap<String, String>();
			// 验签成功入账
			if (BocConstants.B2B_PAY_ORDER_STATUS_SUCCESS.equals(messageB2B.getTranStatus())) {
				param.put("orderId", messageB2B.getOrderId());
				param.put("amt", messageB2B.getAmount().toString());
				param.put("cardType", "Unknown");
				param.put("notifyNum", "1");
				param.put("payStatus", "00");
				param.put("retCode", "00");
				param.put("retMsg", "验签成功");
				param.put("signData", messageB2B.getSignMessage());
				param.put("isFront", String.valueOf(base.isFront()));
				result.setModel("isNotifyCashier", param);
				result.setOrderStatus(true);
			} else {
				// 通知后台地址该订单失败
				param.put("orderId", messageB2B.getOrderId());
				param.put("amt", messageB2B.getAmount().toString());
				param.put("cardType", "Unknown");
				param.put("notifyNum", "1");
				param.put("payStatus", "01");
				param.put("retCode", "01");
				param.put("retMsg", "验签失败");
				param.put("signData", messageB2B.getSignMessage());
				param.put("isFront", String.valueOf(base.isFront()));
				result.setModel("isNotifyCashier", param);
				result.setOrderStatus(false);
			}
		
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	}

	@Override
	public Result query(BaseMessage base) {
		Result result = new Result(false);
		try {
			BocB2bMessage messageB2B = new BocB2bMessage();
			BeanUtils.copyProperties(base, messageB2B);
			BocB2bMessage b2b = (BocB2bMessage) bocB2bManager.query(messageB2B);
			result.setDefaultModel(b2b);
			result.setSuccess(true);
			if(BisPayCheckUtils.checkExternalOrderID(messageB2B.getOrderId())){
				Map<String, String> param = new HashMap<String, String>();
				param.put("orderId", messageB2B.getOrderId());
				param.put("amount", messageB2B.getAmount().toString());
				if (b2b == null) {
					// 查询订单为空
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", "银行返回对账结果为空");
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
				}else if (StringUtils.isNotBlank(b2b.getRtnCode()) && !"00".equals(b2b.getRtnCode())) {
					// 查询订单错误
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", b2b.getRtnMsg());
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
				}else{
					List<BocB2bMessage> bocB2bMessageList = b2b.getList();
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					if (bocB2bMessageList != null && bocB2bMessageList.size() > 0) {
						BocB2bMessage orderRes = (BocB2bMessage) b2b.getList().get(0);
						// 如果订单状态：支付成功
						if (StringUtils.equals(BocConstants.B2B_ORDER_STATUS_SUCCESS,orderRes.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
							param.put("returnMessage", "交易成功");
							/* 以下两个状态，视为订单失败，系统将进行失败账务处理。 */
						} else if (StringUtils.equals(BocConstants.B2B_ORDER_STATUS_EXPIRE,orderRes.getOrderStatus())) {
							//失败处理
							param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
							param.put("returnMessage", "过期失效");
						} else if (StringUtils.equals(BocConstants.B2B_ORDER_STATUS_FAIL,orderRes.getOrderStatus())) {
							//失败处理
							param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
							param.put("returnMessage", "交易失败");
							/* 以下为中间状态，订单状态不改变 */
						} else if (StringUtils.equals(BocConstants.B2B_ORDER_STATUS_EXCEPTION,orderRes.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", "支付异常");
						} else if (StringUtils.equals(BocConstants.B2B_ORDER_STATUS_UNCOMFIRM,orderRes.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", "支付未确认");
						} else if (StringUtils.equals(BocConstants.B2B_ORDER_STATUS_COMFIRM,orderRes.getOrderStatus())) {
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", "支付确认");
						} else {
							// 银行订单状态未明确
							param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
							param.put("returnMessage", "交易结果未明确");
						}
					} else{
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "银行返回无此订单");
					}
				}
				result.setModel("queryResult", param);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6032);
		}
		return result;
	}

	@Override
	public Result dayend(BaseMessage arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result refund(BaseMessage arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}
}
